package com.atguigu.gulimall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.feign.ProductFeignService;
import com.atguigu.gulimall.inteceptor.CartInteceptor;
import com.atguigu.gulimall.service.CartService;
import com.atguigu.gulimall.to.UserInfoTo;
import com.atguigu.gulimall.vo.Cart;
import com.atguigu.gulimall.vo.CartItem;
import com.atguigu.gulimall.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor poolExecutor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> operation = getOperation();


        // 检查购物车是否含有此商品
        String s = (String) operation.get(skuId + "");
        // 表示没有此商品
        if (StringUtils.isEmpty(s)) {
            // 封装cartItem
            CartItem cartItem = new CartItem();

            // 无返回值
            // 1. 封装skuInfo
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                SkuInfoVo skuInfo = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCount(num);
                cartItem.setCheck(true);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setSkuId(skuId);
            }, poolExecutor);

            // 2.封装 AttrValues
            CompletableFuture<Void> getsaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                R saleAttr = productFeignService.getSaleAttr(skuId);
                List<String> saleAttrValues = (List<String>) saleAttr.getData("saleAttrValues", new TypeReference<List<String>>() {
                });
                cartItem.setSkuAttr(saleAttrValues);
            }, poolExecutor);


            // 3. 等待所有结果
            CompletableFuture<Void> all = CompletableFuture.allOf(getSkuInfoTask, getsaleAttrValuesTask);
            try {
                System.out.println(all.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println("cartItem -> " + cartItem);
            operation.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        } else {
            CartItem cartItem2 = JSON.parseObject(s, new TypeReference<CartItem>() {
            });
            cartItem2.setCount(cartItem2.getCount() + num);

            // 重新保存到redis中
            operation.put(skuId.toString(), JSON.toJSONString(cartItem2));
            return cartItem2;
        }


    }

    // 根据 skuId从redis中得到数据
    @Override
    public CartItem getModelForSkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> operation = getOperation();
        String s = (String) operation.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        System.out.println("cartItem ->" + cartItem);
        return cartItem;
    }

    /**
     * 获取购物车内所有商品
     *
     * @return
     */
    @Override
    public Cart getCart() {
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();
        Cart cart = new Cart();
        String userKey = CART_PREFIX + userInfoTo.getUserKey();
        if (userInfoTo.getUserId() != null) {  //表示已登录
            // 将未登录时的购物车加入到已登录的购物车中
            List<CartItem> cartItems = getCartItem(userKey);
            // 加入
            if (cartItems != null && cartItems.size() > 0) {
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
            }
            // 重新获取购物车数据
            List<CartItem> cartItem = getCartItem(CART_PREFIX + userInfoTo.getUserId());
            System.out.println("购物车 -> " + cartItem);
            // 删除原来临时用户的购物车数据
            deleteNoLoginCart(userKey);
            cart.setItems(cartItem);
        } else {
            BoundHashOperations hashOps = redisTemplate.boundHashOps(userKey);
            // 得到的是String类型
            List<Object> values = hashOps.values();
            if (values != null && values.size() > 0) {
                List<CartItem> collect = values.stream().map(item -> {
                    String s = (String) item;
                    CartItem cartItem = JSON.parseObject(s, CartItem.class);
                    return cartItem;
                }).collect(Collectors.toList());
                cart.setItems(collect);
            }
        }
        return cart;
    }

    private CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operation = getOperation();
        String s = (String) operation.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public void cartItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> operation = getOperation();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        // 转换成JSON
        String s = JSON.toJSONString(cartItem);
        operation.put(skuId.toString(), s);
    }

    @Override
    public void changeSkuNum(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> operation = getOperation();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        operation.put(skuId.toString(), s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operation = getOperation();
        operation.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItem() {
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();
        String userId = userInfoTo.getUserId();
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        List<CartItem> cartItem = getCartItem(CART_PREFIX + userId);
        // 1. 我们应该重新查询价格，避免因时间导致的价格不准确
        // 2. 我们去掉未确定的商品
        if (cartItem != null && cartItem.size() > 0) {
            List<CartItem> collect = cartItem.stream().filter(item -> {
                System.out.println(item.getCheck());
                return item.getCheck();
            }).map(obj -> {
                // 远程调用查询价格
                R r = productFeignService.getPriceBySkuId(obj.getSkuId());
                BigDecimal price = (BigDecimal) r.getData("price", new TypeReference<BigDecimal>() {
                });
                obj.setPrice(price);
                return obj;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 删除临时用户购物车
     *
     * @param userKey
     */
    private void deleteNoLoginCart(String userKey) {
        redisTemplate.delete(userKey);
    }

    /**
     * 得到userKey中购物车数据
     *
     * @param userKey
     * @return
     */
    private List<CartItem> getCartItem(String userKey) {
        BoundHashOperations hashOps = redisTemplate.boundHashOps(userKey);
        List<Object> values = hashOps.values();
        List<CartItem> collect = values.stream().map(item -> {
            String s = (String) item;
            CartItem cartItem = JSON.parseObject(s, CartItem.class);
            return cartItem;
        }).collect(Collectors.toList());
        return collect;
    }

    private BoundHashOperations<String, Object, Object> getOperation() {
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        System.out.println("cartKey -> " + cartKey);
        // 绑定该key
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
